import { useState, useEffect } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Slider } from "@/components/ui/slider";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { ModelSettings } from "@/types/chat";
import { AlertCircle, CheckCircle } from "lucide-react";

interface ModelTestStatus {
  chat: "idle" | "testing" | "success" | "error";
  embedding: "idle" | "testing" | "success" | "error";
  errorMessage?: string;
}

interface ModelSettingsFormProps {
  initialSettings?: Partial<ModelSettings>;
  onSave?: (settings: ModelSettings) => void;
}

export function ModelSettingsForm({
  initialSettings,
  onSave,
}: ModelSettingsFormProps) {
  const [settings, setSettings] = useState<ModelSettings>({
    chatModel: {
      type: initialSettings?.chatModel?.type || "openai",
      apiUrl: initialSettings?.chatModel?.apiUrl || "https://api.openai.com/v1/chat/completions",
      apiKey: initialSettings?.chatModel?.apiKey || "",
      model: initialSettings?.chatModel?.model || "gpt-4o",
      temperature: initialSettings?.chatModel?.temperature || 0.7,
      topP: initialSettings?.chatModel?.topP || 1,
      maxTokens: initialSettings?.chatModel?.maxTokens || 1000,
    },
    embeddingModel: {
      type: initialSettings?.embeddingModel?.type || "openai",
      apiUrl: initialSettings?.embeddingModel?.apiUrl || "https://api.openai.com/v1/embeddings",
      apiKey: initialSettings?.embeddingModel?.apiKey || "",
      model: initialSettings?.embeddingModel?.model || "text-embedding-3-small",
    }
  });

  const [testStatus, setTestStatus] = useState<ModelTestStatus>({
    chat: "idle",
    embedding: "idle",
  });

  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [saveSuccess, setSaveSuccess] = useState(false);

  // 加载设置
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await fetch("/api/settings");
        if (response.ok) {
          const data = await response.json();
          if (data.success && data.settings) {
            setSettings(data.settings);
          }
        }
      } catch (error) {
        console.error("加载设置失败:", error);
      }
    };

    loadSettings();
  }, []);

  // 处理聊天模型设置变更
  const handleChatModelChange = (
    field: keyof ModelSettings["chatModel"],
    value: string | number
  ) => {
    setSettings((prev) => ({
      ...prev,
      chatModel: {
        ...prev.chatModel,
        [field]: value,
      },
    }));
  };

  // 处理嵌入模型设置变更
  const handleEmbeddingModelChange = (
    field: keyof ModelSettings["embeddingModel"],
    value: string
  ) => {
    setSettings((prev) => ({
      ...prev,
      embeddingModel: {
        ...prev.embeddingModel,
        [field]: value,
      },
    }));
  };

  // 保存设置
  const handleSaveSettings = async () => {
    try {
      setSaving(true);
      setSaveError(null);
      setSaveSuccess(false);

      const response = await fetch("/api/settings", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ settings }),
      });

      const data = await response.json();

      if (data.success) {
        setSaveSuccess(true);
        if (onSave) {
          onSave(settings);
        }
      } else {
        setSaveError(data.error || "保存设置失败");
      }
    } catch (error) {
      console.error("保存设置失败:", error);
      setSaveError("保存设置失败");
    } finally {
      setSaving(false);
    }
  };

  // 测试模型连接
  const handleTestConnection = async (modelType: "chat" | "embedding") => {
    try {
      setTestStatus((prev) => ({
        ...prev,
        [modelType]: "testing",
        errorMessage: undefined,
      }));

      const modelConfig =
        modelType === "chat" ? settings.chatModel : settings.embeddingModel;

      const response = await fetch("/api/settings/test-model-connection", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          modelType,
          type: modelConfig.type,
          apiUrl: modelConfig.apiUrl,
          apiKey: modelConfig.apiKey,
          model: modelConfig.model,
        }),
      });

      const data = await response.json();

      if (data.success) {
        setTestStatus((prev) => ({
          ...prev,
          [modelType]: "success",
        }));
      } else {
        setTestStatus((prev) => ({
          ...prev,
          [modelType]: "error",
          errorMessage: data.error || "连接测试失败",
        }));
      }
    } catch (error) {
      console.error("测试连接失败:", error);
      setTestStatus((prev) => ({
        ...prev,
        [modelType]: "error",
        errorMessage: "测试连接失败",
      }));
    }
  };

  // 渲染聊天模型设置
  const renderChatModelSettings = () => {
    return (
      <div className="space-y-6">
        <div className="space-y-4">
          <div>
            <Label htmlFor="chat-model-type">模型类型</Label>
            <Select
              value={settings.chatModel.type}
              onValueChange={(value) =>
                handleChatModelChange("type", value)
              }
            >
              <SelectTrigger id="chat-model-type" className="mt-1.5">
                <SelectValue placeholder="选择模型类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="openai">OpenAI</SelectItem>
                <SelectItem value="llama">LLaMA</SelectItem>
                <SelectItem value="custom">自定义</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="chat-api-url">API 地址</Label>
            <Input
              id="chat-api-url"
              value={settings.chatModel.apiUrl}
              onChange={(e) => handleChatModelChange("apiUrl", e.target.value)}
              className="mt-1.5"
            />
          </div>

          <div>
            <Label htmlFor="chat-api-key">API 密钥</Label>
            <Input
              id="chat-api-key"
              type="password"
              value={settings.chatModel.apiKey}
              onChange={(e) => handleChatModelChange("apiKey", e.target.value)}
              className="mt-1.5"
            />
          </div>

          <div>
            <Label htmlFor="chat-model-name">模型名称</Label>
            <Input
              id="chat-model-name"
              value={settings.chatModel.model}
              onChange={(e) => handleChatModelChange("model", e.target.value)}
              className="mt-1.5"
            />
          </div>

          <div>
            <div className="flex justify-between">
              <Label htmlFor="chat-temperature">温度 ({settings.chatModel.temperature})</Label>
            </div>
            <Slider
              id="chat-temperature"
              min={0}
              max={2}
              step={0.1}
              value={[settings.chatModel.temperature]}
              onValueChange={(value) =>
                handleChatModelChange("temperature", value[0])
              }
              className="mt-3"
            />
          </div>

          <div>
            <div className="flex justify-between">
              <Label htmlFor="chat-top-p">Top P ({settings.chatModel.topP})</Label>
            </div>
            <Slider
              id="chat-top-p"
              min={0}
              max={1}
              step={0.1}
              value={[settings.chatModel.topP]}
              onValueChange={(value) =>
                handleChatModelChange("topP", value[0])
              }
              className="mt-3"
            />
          </div>

          <div>
            <Label htmlFor="chat-max-tokens">最大标记数</Label>
            <Input
              id="chat-max-tokens"
              type="number"
              value={settings.chatModel.maxTokens.toString()}
              onChange={(e) =>
                handleChatModelChange("maxTokens", parseInt(e.target.value) || 0)
              }
              className="mt-1.5"
            />
          </div>

          <div>
            <Button
              variant="outline"
              onClick={() => handleTestConnection("chat")}
              disabled={testStatus.chat === "testing"}
              className="w-full"
            >
              {testStatus.chat === "testing"
                ? "测试中..."
                : testStatus.chat === "success"
                ? "测试成功"
                : testStatus.chat === "error"
                ? "测试失败"
                : "测试连接"}
            </Button>

            {testStatus.chat === "success" && (
              <div className="mt-2 flex items-center text-green-500">
                <CheckCircle className="mr-1 h-4 w-4" />
                <span className="text-sm">连接成功</span>
              </div>
            )}

            {testStatus.chat === "error" && (
              <div className="mt-2 flex items-center text-red-500">
                <AlertCircle className="mr-1 h-4 w-4" />
                <span className="text-sm">{testStatus.errorMessage || "连接失败"}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  // 渲染嵌入模型设置
  const renderEmbeddingModelSettings = () => {
    return (
      <div className="space-y-6">
        <div className="space-y-4">
          <div>
            <Label htmlFor="embedding-model-type">模型类型</Label>
            <Select
              value={settings.embeddingModel.type}
              onValueChange={(value) =>
                handleEmbeddingModelChange("type", value)
              }
            >
              <SelectTrigger id="embedding-model-type" className="mt-1.5">
                <SelectValue placeholder="选择模型类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="openai">OpenAI</SelectItem>
                <SelectItem value="custom">自定义</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="embedding-api-url">API 地址</Label>
            <Input
              id="embedding-api-url"
              value={settings.embeddingModel.apiUrl}
              onChange={(e) =>
                handleEmbeddingModelChange("apiUrl", e.target.value)
              }
              className="mt-1.5"
            />
          </div>

          <div>
            <Label htmlFor="embedding-api-key">API 密钥</Label>
            <Input
              id="embedding-api-key"
              type="password"
              value={settings.embeddingModel.apiKey}
              onChange={(e) =>
                handleEmbeddingModelChange("apiKey", e.target.value)
              }
              className="mt-1.5"
            />
          </div>

          <div>
            <Label htmlFor="embedding-model-name">模型名称</Label>
            <Input
              id="embedding-model-name"
              value={settings.embeddingModel.model}
              onChange={(e) =>
                handleEmbeddingModelChange("model", e.target.value)
              }
              className="mt-1.5"
            />
          </div>

          <div>
            <Button
              variant="outline"
              onClick={() => handleTestConnection("embedding")}
              disabled={testStatus.embedding === "testing"}
              className="w-full"
            >
              {testStatus.embedding === "testing"
                ? "测试中..."
                : testStatus.embedding === "success"
                ? "测试成功"
                : testStatus.embedding === "error"
                ? "测试失败"
                : "测试连接"}
            </Button>

            {testStatus.embedding === "success" && (
              <div className="mt-2 flex items-center text-green-500">
                <CheckCircle className="mr-1 h-4 w-4" />
                <span className="text-sm">连接成功</span>
              </div>
            )}

            {testStatus.embedding === "error" && (
              <div className="mt-2 flex items-center text-red-500">
                <AlertCircle className="mr-1 h-4 w-4" />
                <span className="text-sm">{testStatus.errorMessage || "连接失败"}</span>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle>模型设置</CardTitle>
        <CardDescription>配置聊天模型和嵌入模型的参数</CardDescription>
      </CardHeader>
      <CardContent>
        <Tabs defaultValue="chat">
          <TabsList className="mb-6 grid w-full grid-cols-2">
            <TabsTrigger value="chat">聊天模型</TabsTrigger>
            <TabsTrigger value="embedding">嵌入模型</TabsTrigger>
          </TabsList>
          <TabsContent value="chat">{renderChatModelSettings()}</TabsContent>
          <TabsContent value="embedding">
            {renderEmbeddingModelSettings()}
          </TabsContent>
        </Tabs>

        <div className="mt-6 flex justify-end">
          <Button onClick={handleSaveSettings} disabled={saving}>
            {saving ? "保存中..." : "保存设置"}
          </Button>
        </div>

        {saveSuccess && (
          <div className="mt-4 flex items-center text-green-500">
            <CheckCircle className="mr-1 h-4 w-4" />
            <span>设置已保存</span>
          </div>
        )}

        {saveError && (
          <div className="mt-4 flex items-center text-red-500">
            <AlertCircle className="mr-1 h-4 w-4" />
            <span>{saveError}</span>
          </div>
        )}
      </CardContent>
    </Card>
  );
}

export default ModelSettingsForm; 